<template>
	<view class="order-list">
		<!-- 顶部状态栏 -->
		<view class="status-tabs">
			<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
				@tap="switchTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 订单列表 -->
		<scroller class="order-container" @init="initScroller" @down="refreshData" @up="listOrder" :up="optUp" :fixed="false">
			<view class="order-item margin-left-sm margin-right-sm" v-for="(order, index) in orderList" :key="index"
				@click="navigateToOrderDetail(order)">
				<view class="store-info">
					<image src="/static/images/logo.png" class="store-icon"></image>
					<text class="store-name">瑞隆安</text>
					<!-- <text class="order-status text-red">{{ order.orderStatus | dictFind(orderStatusDicts) }}</text> -->
					<text class="order-status text-red" v-if="order.orderStatus ==='0'">未支付</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='1'">待发货</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='-1'">已取消</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='12'">待收货</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='99'">完成</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='0'">审核中</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='-1'">取消退款</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='2'">协商取消</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='3'">待寄回</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='4'">商家待收货</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='99'">已退款</text>
					<text class="order-status text-red" v-if="order.orderStatus ==='3' && order.backStatus==='100'">已清退</text>
				</view>

				<view class="product-info">
					<view class="image-container">
						<image :src="order.orderSpeciDetailVoList[0].image | avatarUrlFind('1')" class="product-image"></image>
						<view v-if="order.isPoints==='1'" class="points-order-tag">积分订单</view>
					</view>
					<view class="product-detail">
						<view class="product-name">{{ order.orderSpeciDetailVoList[0].drugName }}</view>
						<view class="spec-count-row">
							<text class="product-spec">{{ order.orderSpeciDetailVoList[0].speciName }}</text>
							<text class="product-count">x{{ order.totalNum }}</text>
						</view>
						<view class="price-info">
							<text v-if="order.isPoints!=='1'">实付款 ¥{{ order.payableAmount }}</text>
							<text v-if="order.isPoints==='1'">积分消耗： {{ order.payableAmount }}</text>
						</view>
					</view>
				</view>

				<view class="action-buttons">
					<view class="button-wrapper">
						<button class="btn plain" v-if="order.orderStatus==='1' && order.isPoints!=='1'" @click.stop="showRefundModal(order)">
							取消订单
						</button>
						<button class="btn plain" v-if="order.orderStatus==='1'" @click.stop="showModifyAddressModal(order)">
							修改地址
						</button>
						<button class="btn plain" v-if="order.orderStatus==='99'" @click.stop="navigateToGoods(order)">
							再来一单
						</button>
						<button class="btn plain" v-if="order.orderStatus==='12' && order.isPoints!=='1'" @click.stop="navigateToAfter(order)">
							申请售后
						</button>
						<button class="btn plain" v-if="order.orderStatus==='12'" @click.stop="navigateToLogistics(order)">
							查看物流
						</button>
						<button class="btn primary" v-if="order.orderStatus==='12'" @click.stop="confirmReceipt(order)">
							确认收货
						</button>
						<button class="btn plain" v-if="order.orderStatus==='3' && order.isPoints!=='1'" @click.stop="navigateToAfterDetail(order)">
							售后详情
						</button>
					</view>
				</view>
			</view>
		</scroller>

		<!-- 极速退款弹框 -->
		<view class="refund-modal" v-if="showRefundModalFlag" @click="closeRefundModal">
			<view class="modal-content padding-bottom" @click.stop>
				<!-- 关闭按钮 -->
				<view class="close-btn" @click="closeRefundModal">×</view>
				
				<!-- 顶部图形区域 -->
				<view class="modal-header">
					<image src="https://www.ruilongan.com/profile/upload/2025/08/14/tui_20250814173716A002.png" class="refund-icon"></image>
				</view>
				
				<!-- 文字内容区域 -->
				<view class="modal-body">
					<view class="main-headline">享未发货秒退,极速到账</view>
					<view class="description">您信誉良好,本次退款尊享未发秒退服务,<br/>退款秒到账</view>
				</view>
				
				<!-- 按钮区域 -->
				<view class="modal-footer">
					<button class="modal-btn cancel-btn" @click="closeRefundModal">我在想想</button>
					<button class="modal-btn confirm-btn" :disabled="isFastRefunding" :loading="isFastRefunding" @click="confirmFastRefund">
						{{ isFastRefunding ? '处理中...' : `极速退款${currentOrder.payableAmount}` }}
					</button>
				</view>
			</view>
		</view>

		<!-- 修改地址弹框 -->
		<AddAddressModal 
			:visible="showAddressModal" 
			:editData="currentEditOrder ? currentEditOrder.addressData : null" 
			@close="closeAddressModal" 
			@save="handleSaveOrderAddress" 
		/>

		<!-- 确认收货弹框 -->
		<view class="confirm-receipt-modal" v-if="showConfirmReceiptModal" @click="closeConfirmReceiptModal">
			<view class="modal-content padding-bottom" @click.stop>
				<!-- 关闭按钮 -->
				<view class="close-btn" @click="closeConfirmReceiptModal">×</view>
				
				<!-- 顶部图形区域 -->
				<view class="modal-header">
					<image :src="currentReceiptOrder.orderSpeciDetailVoList[0].image | avatarUrlFind('1')" class="receipt-icon"></image>
				</view>
				
				<!-- 文字内容区域 -->
				<view class="modal-body">
					<view class="main-headline">确认收到商品了吗？</view>
					<view class="description">为保障您的售后权益请确认无误后再确认收货</view>
				</view>
				
				<!-- 按钮区域 -->
				<view class="modal-footer">
					<button class="modal-btn cancel-btn" @click="closeConfirmReceiptModal">我再想想</button>
					<button class="modal-btn confirm-btn" :disabled="isConfirmingReceipt" :loading="isConfirmingReceipt" @click="handleConfirmReceipt">
						{{ isConfirmingReceipt ? '处理中...' : '确认收货' }}
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import scroller from '@/components/scroller/scroller.vue';
	import AddAddressModal from '@/components/AddAddressModal.vue';
	import {
		listOrder,
		confirmReceipt,
		quickRefund,
		updateOrderAddress
	} from '@/api/order.js'
	import {
		listAddress
	} from '@/api/userAddress.js'
	import {
		mapGetters
	} from "vuex"
	import {
		getInfoByDrugCode
	} from '@/api/shop.js'

	export default {
		components: {
			scroller,
			AddAddressModal
		},
		computed: mapGetters(['userId', 'name']),
		data() {
			return {
				orderStatusDicts: [],
				currentTab: 0,
				scroller: {},
				optUp: {
					onScroll: true, //监听滚动事件
					page: {
						size: 5
					} //下拉加载15条
				},
				queryParams: {},
				tabs: ['全部', '待发货', '待收货', '已完成', '售后/退款'],
				orderList: [
					// {
					// 	id: 1,
					// 	storeName: '瑞隆安',
					// 	productName: '法式长袖碎花裙子高级感长裙荷叶边仙女连衣裙',
					// 	productImage: 'https://picsum.photos/200/200',
					// 	size: 'S',
					// 	color: '青色',
					// 	count: 1,
					// 	price: '398.00',
					// 	status: {
					// 		text: '待发货',
					// 		className: 'waiting-ship'
					// 	},
					// 	buttons: [{
					// 			text: '取消订单',
					// 			type: 'plain',
					// 			action: 'cancel'
					// 		},
					// 		{
					// 			text: '修改地址',
					// 			type: 'plain',
					// 			action: 'modifyAddress'
					// 		}
					// 	]
					// }
				],
				showRefundModalFlag: false,
				currentOrder: null,
				orderStatus:'',
				isFastRefunding: false,
				// 修改地址相关
				showAddressModal: false,
				currentEditOrder: null,
				addressList: [],
				// 确认收货相关
				showConfirmReceiptModal: false,
				currentReceiptOrder: null,
				isConfirmingReceipt: false
			}
		},
		created() {
			this.$dict.getDicts('order_status').then(res => {
				this.orderStatusDicts = res.data
			})
		},
		onLoad(options) {
			// 接收来自“我的-订单入口”的状态，定位到对应tab
			const status = options && options.status
			if (status === 'pending') {
				this.currentTab = 1
				this.orderStatus = '1'
			} else if (status === 'received') {
				this.currentTab = 2
				this.orderStatus = '12'
			} else if (status === 'completed') {
				this.currentTab = 3
				this.orderStatus = '99'
			} else if (status === 'refund') {
				this.currentTab = 4
				this.orderStatus = '3'
			} else {
				this.currentTab = 0
				this.orderStatus = ''
			}
		},
		onBackPress() {
			// 返回到我的页面，而不是之前的页面
			uni.switchTab({
				url: '/pages/mine/index'
			});
			return true; // 阻止默认返回行为
		},
		methods: {
			
			/*初始化滚动*/
			initScroller(scroller) {
				this.scroller = scroller;
			},
			/*刷新数据*/
			refreshData() {
				this.loadData()
			},
			/*加载数据*/
			loadData() {
				this.orderList = [];
				this.scroller.resetUpScroll();
			},
			
			switchTab(index) {
				this.currentTab = index
				// 这里可以根据tab切换请求不同状态的订单数据
				if(index===0){
					this.orderStatus=''
				}else if(index===1){
					this.orderStatus='1'
				}else if(index===2){
					this.orderStatus='12'
				}else if(index===3){
					this.orderStatus='99'
				}else if(index===4){
					this.orderStatus='3'
				}
				this.loadData()
			},
			handleButton(action, order) {
				switch (action) {
					case 'cancel':
						// 处理取消订单
						break
					case 'modifyAddress':
						// 处理修改地址
						break
					case 'afterSale':
						// 处理申请售后
						break
					case 'checkLogistics':
						// 处理查看物流
						break
					case 'confirmReceive':
						// 处理确认收货
						break
					case 'reorder':
						// 处理再次购买
						break
				}
			},
			navigateToOrderDetail(order) {
				if(order.backStatus==='3'){
					uni.navigateTo({
						url: `/subPackage_1/pages/order/after-sale-detail?order=`+encodeURIComponent(JSON.stringify(order))
					})
				}else if(order.orderStatus==='3' && order.backStatus !=='3'){
					uni.navigateTo({
						url: `/subPackage_1/pages/order/order-detail?orderId=${order.id}`
					})
				}else{
					uni.navigateTo({
						url: `/subPackage_1/pages/order/order-detail?orderId=${order.id}`
					})
				}
			},
			
			navigateToLogistics(order) {
				uni.navigateTo({
					url: `/subPackage_1/pages/order/see_logistics?orderId=${order.id}`
				})
			},
			
			navigateToAfter(order){
				uni.navigateTo({
					url: `/subPackage_1/pages/order/apply-after?order=`+encodeURIComponent(JSON.stringify(order))
				})
			},
			
			navigateToAfterDetail(order){
				if(order.backStatus==='3'){
					uni.navigateTo({
						url: `/subPackage_1/pages/order/after-sale-detail?order=`+encodeURIComponent(JSON.stringify(order))
					})
				}else if(order.orderStatus==='3' && order.backStatus !=='3'){
					uni.navigateTo({
						url: `/subPackage_1/pages/order/order-detail?orderId=${order.id}`
					})
				}
				
			},
			
			async listOrder() {
				this.queryParams.pageNum = this.scroller.num
				this.queryParams.pageSize = this.scroller.size
				this.queryParams.orderStatus = this.orderStatus
				this.queryParams.userId = this.userId
				const {
					rows,
					total
				} = await listOrder(this.queryParams)
				console.log('------商品列表------', rows)
				this.orderList = this.orderList.concat(rows);
				this.$forceUpdate();
				this.scroller.endBySize(rows.length, total);
				uni.stopPullDownRefresh();
				uni.hideLoading();
			},
			
			// 显示确认收货弹窗
			confirmReceipt(order) {
				this.currentReceiptOrder = order;
				this.showConfirmReceiptModal = true;
			},

			// 关闭确认收货弹窗
			closeConfirmReceiptModal() {
				this.showConfirmReceiptModal = false;
				this.currentReceiptOrder = null;
			},

			// 处理确认收货
			async handleConfirmReceipt() {
				if (!this.currentReceiptOrder || this.isConfirmingReceipt) return;
				
				this.isConfirmingReceipt = true;
				uni.showLoading({
					title: '处理中...',
					mask: true
				});
				
				try {
					const res = await confirmReceipt(this.currentReceiptOrder);
					if (res && res.code === 200) {
						console.log('确认收货成功:', res);
						uni.showToast({
							title: '确认收货成功',
							icon: 'success'
						});
						this.loadData();
						this.closeConfirmReceiptModal();
					} else {
						uni.showToast({
							title: res.msg || '确认收货失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('确认收货失败:', error);
					uni.showToast({
						title: '确认收货失败，请重试',
						icon: 'none'
					});
				} finally {
					this.isConfirmingReceipt = false;
					uni.hideLoading();
				}
			},

			showRefundModal(order) {
				this.currentOrder = order;
				this.showRefundModalFlag = true;
			},
			closeRefundModal() {
				this.showRefundModalFlag = false;
				this.currentOrder = null;
			},
			async confirmFastRefund() {
				if (!this.currentOrder || this.isFastRefunding) return;
				this.isFastRefunding = true;
				uni.showLoading({
					title: '处理中...',
					mask: true
				});
				try {
					const res = await quickRefund({ orderId: this.currentOrder.id });
					if (res && res.code === 200) {
						console.log('极速退款成功:', res);
						uni.showToast({
							title: '极速退款成功',
							icon: 'success'
						});
						this.loadData();
						this.closeRefundModal();
					}
				} catch (error) {
					console.error('极速退款失败:', error);
					uni.showToast({
						title: '极速退款失败',
						icon: 'none'
					});
				} finally {
					this.isFastRefunding = false;
					uni.hideLoading();
				}
			},

			// 显示修改地址弹框
			showModifyAddressModal(order) {
				this.currentEditOrder = order;
				// 构建地址数据用于回显
				if (order.address) {
					this.currentEditOrder.addressData = {
						id: order.addressId || null,
						realName: order.receiverName || '',
						phone: order.receiverPhone || '',
						province: order.province || '',
						city: order.city || '',
						district: order.district || '',
						detail: order.address || '',
						region: (order.province || '') + (order.city || '') + (order.district || '')
					};
				}
				this.showAddressModal = true;
			},

			// 关闭修改地址弹框
			closeAddressModal() {
				this.showAddressModal = false;
				this.currentEditOrder = null;
			},

			// 保存订单地址修改
			async handleSaveOrderAddress(addressData) {
				console.log('addressData', addressData)
				if (!this.currentEditOrder) return;
				
				try {
					uni.showLoading({
						title: '保存中...',
						mask: true
					});

					// 构建更新订单的数据
					const updateData = {
						orderId: this.currentEditOrder.id,
						receiveUserName: addressData.realName,
						receiveUserPhone: addressData.phone,
						receiveProvince: addressData.province,
						receiveCity: addressData.city,
						receiveCounty: addressData.district,
						receiveUserAddress: addressData.detail,
						addressId: addressData.id || null,
						receiveProvince: addressData.province,
						receiveCity: addressData.city,
						receiveCounty: addressData.district,
					};

					const res = await updateOrderAddress(updateData);
					if (res && res.code === 200) {
						uni.showToast({
							title: '地址修改成功',
							icon: 'success'
						});
						// 刷新订单列表
						this.loadData();
						this.closeAddressModal();
					} else {
						uni.showToast({
							title: res.msg || '修改失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('修改地址失败:', error);
					uni.showToast({
						title: '修改失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			navigateToGoods(order){
				getInfoByDrugCode(order.orderSpeciDetailVoList[0].drugCode).then(res=>{
					uni.navigateTo({
						url: `/subPackage_1/pages/goods/good-detail?id=`+ res.data.id
					})
				})
			}
			
		}
	}
</script>

<style>
	.order-list {
		min-height: 100vh;
		background-color: #f8f8f8;
	}

	.status-tabs {
		display: flex;
		background-color: #fff;
		padding: 0 20rpx;
		position: sticky;
		top: 0;
		z-index: 1;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #333;
		position: relative;
	}

	.tab-item.active {
		color: #000;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #000;
		border-radius: 2rpx;
	}

	.order-container {
		padding: 20rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.store-info {
		display: flex;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.store-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}

	.store-name {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	.order-status {
		font-size: 26rpx;
	}

	.order-status.waiting-ship {
		color: #ff4d4f;
	}

	.order-status.waiting-receive {
		color: #ff4d4f;
	}

	.order-status.completed {
		color: #999;
	}

	.product-info {
		display: flex;
		padding: 20rpx 0;
	}

	.image-container {
		position: relative;
		margin-right: 20rpx;
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.points-order-tag {
		position: absolute;
		top: 0rpx;
		left: 0rpx;
		background-color: #FFCC00;
		color: #fff;
		font-size: 20rpx;
		padding: 4rpx 8rpx;
		border-bottom-right-radius: 12rpx;
		line-height: 1.2;
		z-index: 1;
	}

	.product-detail {
		flex: 1;
	}

	.product-name {
		font-size: 30rpx;
		color: #000;
		margin-bottom: 10rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.spec-count-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
	}

	.product-count {
		font-size: 24rpx;
		color: #999;
	}

	.price-info {
		text-align: right;
		font-size: 30rpx;
		color: #000;
		padding: 10rpx 0;
		margin-top: 10rpx;
	}

	.action-buttons {
		padding-top: 20rpx;
		border-top: 1rpx solid #f5f5f5;
	}

	.button-wrapper {
		display: flex;
		justify-content: flex-end;
		gap: 15rpx;
	}

	.btn {
		margin: 0;
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		border-radius: 12rpx;
		min-width: 120rpx;
		height: 60rpx;
		line-height: 44rpx;
	}

	.btn.plain {
		background-color: #fff;
		border: 1rpx solid #ddd;
		color: #666;
	}

	.btn.primary {
		background-color: #07c160;
		color: #fff;
		border: none;
	}

	/* 极速退款弹框样式 */
	.refund-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: flex-end;
		align-items: flex-end;
		z-index: 1000;
	}

	.modal-content {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		width: 100%;
		overflow: hidden;
		position: relative;
		transform: translateY(100%);
		animation: slideUp 0.3s ease-out forwards;
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}
		to {
			transform: translateY(0);
		}
	}

	.close-btn {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 40rpx;
		color: #999;
		z-index: 1;
	}

	.modal-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0 20rpx;
		/* background-color: #f0f0f0; */
	}

	.refund-icon {
		width: 280rpx;
		height: 280rpx;
		margin-bottom: 20rpx;
	}

	.fast-refund-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-top: 10rpx;
	}

	.modal-body {
		padding: 20rpx;
		text-align: center;
		padding-top: 10rpx;
	}

	.main-headline {
		font-size: 36rpx;
		/* font-weight: bold; */
		color: #000;
		margin-bottom: 10rpx;
	}

	.description {
		font-size: 24rpx;
		color: #979797;
		line-height: 1.5;
	}

	.modal-footer {
		display: flex;
		justify-content: space-around;
		padding: 20rpx;
		/* border-top: 1rpx solid #f0f0f0; */
	}

	.modal-btn {
		flex: 1;
		margin: 0 10rpx;
		padding: 20rpx 20rpx;
		font-size: 32rpx;
		border-radius: 15rpx;
		border: none;
		line-height: 1;
	}

	.modal-btn.cancel-btn {
		background-color: #f8f8f8;
		color: #4cd080;
	}

	.modal-btn.confirm-btn {
		background-color: #4cd080;
		color: #fff;
	}

	/* 确认收货弹框样式 */
	.confirm-receipt-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: flex-end;
		align-items: flex-end;
		z-index: 1000;
	}

	.receipt-icon {
		width: 280rpx;
		height: 280rpx;
		margin-bottom: 20rpx;
	}
</style>